#include "mystring.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void Init_string(mystring *obj,const char *str);
void Print(mystring *obj);
int Size1(mystring *obj);
int Isequal(mystring *obj1,mystring *obj2);
int Iscontains(mystring *obj1,mystring *obj2);
char* Atindex(mystring *obj,int index);
void Removestring(mystring *obj,const char *p);
void Insertstring(mystring *obj1,const char *p,int index);
int Toint(mystring *obj);
double Todouble (mystring *obj);


void Init_string(mystring *obj, const char *str)
{
    obj->size=strlen(str);
    strcpy(obj->string,str);
    
    obj->print=Print;
    obj->isequal=Isequal;
    obj->size=Size1;
    obj->atindex=Atindex;
    obj->insertstring=Insertstring;
    obj->removestring=Removestring;
    obj->iscontains=Iscontains;
    obj->toint=Toint;
    obj->todouble=Todouble;
}

void Print(mystring *obj)
{
    printf("%s\n",obj->string);
}

int Size1(mystring *obj)
{
    return obj->size;
}

int Isequal(mystring *obj1, mystring *obj2)
{
    if(strcmp(obj1->string,obj2->string)==0)
        return 1;
    return 0;
}

int Iscontains(mystring *obj1, mystring *obj2)
{
    char *equal=strstr(obj1->string,obj2->string);
    if(equal==NULL)
        return 0;
    else
        return 1;
}

char* Atindex(mystring *obj, int index)
{
    if(index>=obj->size||index<0)
        return NULL;
    char *p=obj->string;
    while(index!=0)
    {
        p++;
        index--;
    }
    return p;
}

void Removestring(mystring *obj, const char *p)
{
    char *ptr=strstr(obj->string,p);
    if(ptr==NULL)
        return;
    else
    {
        char *back=ptr+strlen(p);
        while(*back!='\0')
        {
            *ptr++=*back++;
        }
        *ptr='\0';
        obj->size=strlen(obj->string);
    }
}

void Insertstring(mystring *obj1,const char *p, int index)
{
    if(index<0||index>obj1->size)
        return;
    char new_str[MAX]={0};
    strncpy(new_str,obj1->string,index);
    strncpy(new_str+index,p,strlen(p));
    strcpy(new_str+index+strlen(p),obj1->string+index);
    memset(obj1->string,0,MAX);
    strcpy(obj1->string,new_str);
    obj1->size=strlen(obj1->string);
}

int Toint(mystring *obj)
{
    return atoi(obj);
}

double Todouble(mystring *obj)
{
    return atof(obj);
}
